import { createStore } from 'vuex'

export default createStore({
  state: {
    cartList: {
      // 第一层是商铺的id
      // shopId: {
      // 第二层是商品的信息
      // productId: {
      //   _id: '1',
      //   name: '番茄 250g / 份',
      //   imgUrl: 'http://www.dell-lee.com/imgs/vue3/tomato.png',
      //   sales: 10,
      //   price: 33.6,
      //   oldPrice: 39.6
      // }
      // }
    }
  },
  getters: {
  },
  mutations: {
    // 接收addItemToCart传来的方法更改数据
    changeCartItemInfo (state, payload) {
      const { shopId, productId, productInfo } = payload
      let shopInfo = state.cartList[shopId]
      if (!shopInfo) { shopInfo = {} }

      // 先去store状态里面获取，如果能获取到，购买数量+1，加好的数据重新存户
      let product = shopInfo[productId]
      // 如果一开始没有数据，那么就给默认
      if (!product) {
        product = productInfo // 不存在直接拿info里面的数据
        product.count = 0 // 当你第一次添加产品的时候count为0
      }
      product.count = product.count + payload.num
      if (payload.num > 0) { product.check = true }
      // 商品数量不能小于0
      if (product.count < 0) { product.count = 0 }
      shopInfo[productId] = product
      state.cartList[shopId] = shopInfo
      console.log(shopInfo)
    },
    changeCartItemChecked (state, payload) {
      const { shopId, productId } = payload
      const product = state.cartList[shopId][productId]
      product.check = !product.check
    },
    // 清空购物车
    cleanCartProducts (state, payload) {
      const { shopId } = payload
      state.cartList[shopId] = {}
    },
    // 全选
    setCartItemsChecked (state, payload) {
      const { shopId } = payload
      const products = state.cartList[shopId]
      if (products) {
        for (const key in products) {
          const product = products[key]
          product.check = true
        }
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
